package com.cyanite.playlv2;

import com.cyanite.playlv2.app.LoadableListActivityWithView;
import com.cyanite.playlv2.widget.FocusSubTripListAdapter;
import com.cyanite.playlv2api.types.Group;
import com.cyanite.playlv2api.types.Task;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class TasksActivity extends LoadableListActivityWithView{

    public static final String EXTRA_TRIP_ID = PlayLv2.PACKAGE_NAME
        + ".TasksActivity.EXTRA_TRIP_ID";

    private StateHolder mStateHolder;
    private FocusSubTripListAdapter mFocusSubTripListAdapter;

    private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));

        mStateHolder = new StateHolder();
        if (getIntent().hasExtra(EXTRA_TRIP_ID)) {
            mStateHolder.setTripId(getIntent().getExtras().getString(EXTRA_TRIP_ID));
        }   else {
            finish();
            return;
        }

        PlayLv2 playlv2 = (PlayLv2)getApplication();
        if (playlv2.isReady()) {
            mStateHolder.startTaskGetTasks(this);
        }
        ensureUi();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();

        if (isFinishing()) {
            unregisterReceiver(mLoggedOutReceiver);
            mStateHolder.cancel();
        }
    }

    private void ensureUi() {
        setTitle(getString(R.string.task_activity_label));

        ListView listView = getListView();
        listView.setDividerHeight(0);
        listView.setOnItemClickListener(new ListView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Task task = (Task) parent.getAdapter().getItem(position);
                Intent intent = new Intent(TasksActivity.this, AddTipsActivity.class);
                intent.putExtra(AddTipsActivity.EXTRA_TASK_PARCEL, task);
                startActivity(intent);
            }
        });

        if (mStateHolder.getIsRunningGetTasks()) {
            setLoadingView();
        }
    }

    private FocusSubTripListAdapter.ButtonRowClickHandler btnOnClickListenerFocus = new FocusSubTripListAdapter.ButtonRowClickHandler(){
        @Override
        public void onImageClick(Task task) {
            Bitmap bitmapOriginal = null;
            if (task.getPhotoBitmap() != null)  {
                bitmapOriginal = task.getPhotoBitmap();
            }   else {
                bitmapOriginal = BitmapFactory.decodeResource(TasksActivity.this.getResources(), R.drawable.trip_default_photo);
            }
            if (bitmapOriginal != null) {
                ShowImageDialog dlg = new ShowImageDialog(TasksActivity.this, bitmapOriginal,
                                                                        getWindowManager().getDefaultDisplay().getWidth());
                dlg.show();
            }
        }
        @Override
        public void onMoreClick() {
        }
    };

    private void onTaskStart() {
        setLoadingView();
    }

    private void onGetTasksComplete(Group<Task> tasks, Exception ex) {
        mStateHolder.setIsRunningGetTasks(false);

        if ( tasks != null && tasks.size() > 0 ) {
            mStateHolder.setTasks(tasks);
            mFocusSubTripListAdapter = new FocusSubTripListAdapter(this,
                    ((PlayLv2) getApplication()).getRemoteResourceManager(), btnOnClickListenerFocus, false);
            mFocusSubTripListAdapter.setGroup(tasks);
            getListView().setAdapter(mFocusSubTripListAdapter);
        }
    }

     private static class TaskGetTasks extends AsyncTask<Void, Void, Group<Task>> {

         private TasksActivity mActivity;
         private Exception mException;
         private String mTripId;

         public TaskGetTasks(TasksActivity activity, String tripId) {
             mActivity = activity;
             mTripId = tripId;
         }

         @Override
         public Group<Task> doInBackground(Void... params) {
             try {
                 return ((PlayLv2) mActivity.getApplication()).getPlayLv2Api().tasks(mTripId);
             } catch (Exception ex) {
                 mException = ex;
                 return null;
             }
         }

         @Override
         protected void onPreExecute() {
             mActivity.onTaskStart();
         }

         @Override
         public void onPostExecute(Group<Task> tasks) {
             if (mActivity != null) {
                 mActivity.onGetTasksComplete(tasks, mException);
             }
         }
     }

    private static class StateHolder {

        private boolean mIsRunningGetTasks;
        private TaskGetTasks mTaskGetTasks;
        private Group<Task> mTasks;
        private String mTripId;

        public StateHolder() {
            mIsRunningGetTasks = false;
        }

        public String getTripId()   {
            return mTripId;
        }

        public void setTripId(String tripId)    {
            mTripId = tripId;
        }

        public Group<Task> getTasks() {
            return mTasks;
        }

        public void setTasks(Group<Task> tasks) {
            mTasks = tasks;
        }

        public boolean getIsRunningGetTasks() {
            return mIsRunningGetTasks;
        }

        public void setIsRunningGetTasks(boolean isRunning) {
            mIsRunningGetTasks = isRunning;
        }


        public void startTaskGetTasks(TasksActivity activity) {
            if ( !mIsRunningGetTasks ) {
                mTaskGetTasks = new TaskGetTasks(activity, mTripId);
                mTaskGetTasks.execute();
                mIsRunningGetTasks = true;
            }
        }

        public void cancel() {
            if (mIsRunningGetTasks) {
                mTaskGetTasks.cancel(true);
                mIsRunningGetTasks = false;
            }
        }
    }
}
